//
//  WMHTMLView.m
//  ChannelSoftWeMarketing
//
//  Created by channelsoftios on 17/8/3.
//  Copyright © 2017年 channelsoftios. All rights reserved.
//

#import "WMHTMLView.h"

@interface WMHTMLView ()

@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation WMHTMLView

- (void)dealloc {
    
    if (_showProgressView) {
        [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    }
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.showProgressView = YES;
        [self webViewInit];
    }
    return self;
}

- (void)setWebViewRect:(CGRect)webViewRect {
    _webViewRect = webViewRect;
    
    _webView.frame = webViewRect;
}

- (void)webViewInit {
    
    if (!_webView) {
        _webView = [[WKWebView alloc] init];        
        [self addSubview:_webView];
    }
    
    if (self.showProgressView) {
        if (!_progressView) {
            _progressView = [[UIProgressView alloc] init];
            _progressView.frame = CGRectMake(self.webViewRect.origin.x, CGRectGetMinY(self.webViewRect), CGRectGetWidth(self.webViewRect),2);
        }
        [self addSubview:_progressView];
        
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    }
    else {
        _progressView = nil;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
     [self addWebview];
    NSLog(@"layoutSubviews");
}

- (void)addWebview {
    if (!_webView) {
        [self webViewInit];
    }
    NSLog(@"webViewInit");

    _webView.frame = self.webViewRect;
    _webView.scrollView.scrollEnabled = self.canScroll;
    NSLog(@"webViewInit_webViewRect%@",NSStringFromCGRect(self.webViewRect));

    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.htmlUrl]]];
    NSLog(@"webViewInit_htmlUrl%@",self.htmlUrl);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    NSLog(@" %s,change = %@",__FUNCTION__,change);
    
    if ([keyPath isEqual: @"estimatedProgress"] && object == _webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:_webView.estimatedProgress animated:YES];
        if(_webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


@end
